import * as fs from 'fs'
import * as util from 'util'
import * as csv from 'csv'

// export csv.generate({ seed: 1, columns: 2, length: 20 }, (err, data) => {
//   if (err) console.log(err)
//   csv.parse(data, (err, data) => {
//     if (err) console.log(err)
//     csv.transform(data, data => {
//       return data.map(value => { return value.toUpperCase() })
//     }, (err, data) => {
//       if (err) console.log(err)
//       csv.stringify(data, (err, data) => {
//         if (err) console.log(err)
//         process.stdout.write(data)
//       })
//     })
//   })
// })

export const loadFile = async fileName => {
  const exists = await util.promisify(fs.exists)(fileName)
  // console.log('loadFile fs.exists', exists)
  if (exists) {
    const data = await util.promisify(fs.readFile)(fileName)
    // console.log('loadFile fs.readFile', data)
    const chunks = await util.promisify(csv.parse)(data, {})
    // console.log('loadFile csv.parse', chunks)
    return chunks
  }
  return null
}

export const toJson = async (chunks, withHeader) => {
  const results = { header: {}, total: 0, chunksData: [] as any[] }
  if (chunks.length) {
    results.total = chunks.length - 1
    chunks.forEach((dataRow, num) => {
      if (withHeader && !num) {
        dataRow.forEach(val => {
          results.header[val] = val
        })
      } else {
        // const rowJson = {}
        // headerRow.forEach((header, index) => {
        //   rowJson[header] = dataRow[index]
        // })
        // let rowJson = Object.assign({}, results.header)
        // rowJson = Object.assign(rowJson, dataRow)
        // console.log(rowJson)
        results.chunksData.push(dataRow)
      }
    })
  }
  return results
}
